﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Common.SqlSugar
{
    public abstract class BaseService<T> : SimpleClient<T>, IBaseService<T> where T : class, new()
    {
        public BaseService(ISqlSugarClient db)
        {
            Context = db;
            //创建数据库
            //db.DbMaintenance.CreateDatabase();
            ////通过反射加载程序集,，查找需要加载的命名空间下的实体
            //Type[] ass = Assembly.LoadFrom(AppContext.BaseDirectory + "MyBlog.Model.dll").GetTypes().Where(p => p.Namespace == "MyBlog.Model.Entity").ToArray();
            ////根据创建创建表（设置字段默认长度为200）
            //db.CodeFirst.SetStringDefaultLength(200).InitTables(ass);
        }
        public async Task<bool> AddAsync(T entity)
        {
            return await base.InsertAsync(entity);
        }
        public async Task<long> AddAndReturnIdAsync(T entity)
        {
            return Context.Insertable<T>(entity).ExecuteReturnSnowflakeId();
        }

        public async Task<bool> DeleteAsync(int id)
        {
            return await base.DeleteByIdAsync(id);
        }

        public async Task<bool> ModifyAsync(T entity)
        {
            return await base.UpdateAsync(entity);
        }
        public async Task<List<T>> QueryAsync()
        {
            return await base.GetListAsync();
        }

        public async Task<List<T>> QueryAsync(Expression<Func<T, bool>> expression)
        {
            return await base.GetListAsync(expression);
        }

        public async Task<List<T>> QueryAsync(int page, int size, RefAsync<int> total)
        {
            return await Context.Queryable<T>().ToPageListAsync(page, size, total);
        }

        public async Task<List<T>> QueryAsync(Expression<Func<T, bool>> expression, int page, int size, RefAsync<int> total)
        {
            return await Context.Queryable<T>()
                .Where(expression)
                .ToPageListAsync(page, size, total);
        }

        public async Task<T> FindAsync(int id)
        {
            try
            {

                return await base.GetByIdAsync(id);
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        public async Task<T> FindAsync(Expression<Func<T, bool>> expression)
        {
            return await base.GetFirstAsync(expression);
        }

    }
}
